<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<link rel="stylesheet" type="text/css" href="Monitor.css" />
        <title>DD Monitor</title>
		<script>
			/* Page refresh  */
			function timedRefresh(timeoutPeriod) {
				setTimeout("location.reload(true);",timeoutPeriod);
			}
		</script>
    </head>
	<!--Refresh page every 5 minutes-->
    <body onload="JavaScript:timedRefresh(300000);"> 

        <?php
        require_once("./DbConnect.inc"); // Contains connection string
        require_once("./DDsettings.inc"); // Contains users and processes
		require_once("./Package.php"); // Contains package class definition
		
		$activePackages = array();
		
		// create empty two dimensional array
		foreach ($DDmembers as $user) {
			foreach ($ProcesList as $proces) {
				$tableContent[$user][$proces] = "";
			}
		}
      
        $query = "SELECT UnitId, Name, LEFT(SubNo, 8) AS intakeDate, REPLACE(ISNULL([Assigned User], 'Not Assigned'), '  ',' ') 
            AS [Assigned User], Proces, Status	FROM internalShowUnits 
            WHERE (Status = 'Waiting' OR Status = 'In Progress') 
            AND Name NOT LIKE '% MSM %' AND UnitType = 'Application'
            ORDER BY Name";

        try{
            $conn = new PDO($dsn, $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // echo "Connection established";
        } catch(PDOException $e){
            echo "Connection failed: " . $e->getMessage();
        }
        
        try {
		    // Fill array with active packages
            $rows = $conn->query($query);
        
            foreach ($rows as $row) {
                    $name = $row["Name"];
                    $user = $row["Assigned User"];
                    $proces = $row["Proces"];
					$status = $row["Status"];
					$intakeDate = DateTime::createFromFormat('Ymd', $row["intakeDate"]); // 19980616 datetime object
					If (!$intakeDate) {
						$intakeDate = DateTime::createFromFormat('d-m-Y', '1-1-1999'); // this should not happen. It means the SubNo is not correct.
					}
					$package = new Package($name, $user, $proces, $status, $intakeDate, '24-9-2013');
					$activePackages[] = $package;
            }
        } catch(PDOException $e) {
            echo "Query failed: " . $e->getMessage();
        }

		// Fill two dimensional array with table content
		foreach ($activePackages as $pkg) {
			switch (progress($pkg)) {
				case 0:
					$color = "black";
					break;
				case 1:
					$color = "orange";
					break;
				case 2:
					$color = "red";
					break;
				default:
					$color = "green";
				}
				
			$tempLeft = "<FONT COLOR=$color>";
			$tempRight = "</FONT><BR>";	
			
			if ($pkg->getCurrentStatus() == 'Waiting'){
				$tempLeft .= "<B>";
				$tempRight .= "</B>";
			}
			
			$tableContent[$pkg->getAssignedUser()][$pkg->getCurrentProces()] .= $tempLeft . $pkg->getName() . $tempRight;
		}

		print("<B>" . date("d F Y   H:i:s", time()) . "</B><BR><BR>");	
		
		// Print table
        print("<TABLE><TH></TH>"); // this is an empty header for the user column.
        foreach ($ProcesList as $proces) {
			print("<TH>$proces</TH>\n");
		}
		foreach ($DDmembers as $user) {
			$row = "<TR><TH>$user</TH>";
			foreach ($ProcesList as $proces) {
				$row .= "<TD>" . $tableContent[$user][$proces] . "</TD>";
			}
			$row .= "</TR>";
			print($row);
		}
        print('</TABLE>');
		
		// Returns 0:Packaging is on track 1:Needs attention 2:Overdue
		function progress(Package $package) {
			global $showProgressIndication;
			global $ProcesList;
			global $defaultDays;
			
			if ($showProgressIndication) {
				$today = new DateTime("now");
				// $procesIndex 0:INV 1:IB-O 2:PKG-O 3:PKG-T 4:PKG-A 5:PKG-P 6:DISTR-T 7:DISTR-F
				$procesIndex = array_search($package->getCurrentProces(), $ProcesList);
				$daysNeeded = 2 * (count($ProcesList) - $procesIndex);
				$start = $package->getStartDate();
				$odaysPast = date_diff($start, $today); // type opbject. days past since intake
				$daysPast = $odaysPast->format('%r%a'); // type string
				// return ($daysPast + $daysNeeded);
				
				If (($daysPast + $daysNeeded) > $defaultDays) {
					return 2; // this means package is behind schedule
				} elseif (($daysPast + $daysNeeded) == $defaultDays) {
					return 1; // warning level
				} else {
					return 0 ; // all fine
				}
			}
			else {
				return 0 ;
			}
		}
        ?>
    </body>
</html>
